﻿using Common;
using DBUtility;
using DeliveryManage.Models;
using Maticsoft.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using DeliveryManage.Model;

namespace DeliveryManage.Controllers
{
    public class UserController : BaseController
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;
        #region 返回用户每页数量=========================
        private int GetPageSize(int _default_size, string CookieName)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie(CookieName, "FxManage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 用户信息
        public ActionResult UserList()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("UserManage", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            int userid = 0;
            this.pageSize  = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);
            userid = DTRequest.GetQueryInt("uid");
            if (userid <= 0)
            {
                DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                userid = model.Id;
            }

            ViewData["SelectUser"] = userid;
            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            #region 搜索
            string keywords = DTRequest.GetQueryString("keywords").Trim();
            string where = string.Format(" TopUser={0}", userid);
            if (!string.IsNullOrEmpty(keywords))
            {
                //模糊查询
                if (keywords.IndexOf("*") >= 0)//判断字符串中是否包含字符串*号
                {
                    where += string.Format(" and (Telephone like '{0}' or Name like '{0}' or Nickname like'{0}')", keywords.Replace("*", "%"));
                }
                else
                {
                    where += string.Format(" and (Telephone like '%{0}%'  or Name like '%{0}%' or Nickname like '%{0}%')", keywords);
                }
                ViewBag.Keyword = keywords;
            }
            
            #endregion
            List<DeliveryManage.Model.Sys_User> list = new List<DeliveryManage.Model.Sys_User>();
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            list = dal.GetQueryList(this.pageSize, this.page, where, "Id asc", out this.totalCount);
            ViewBag.UserList = list;

            Dictionary<int, string> dicRole = new Dictionary<int, string>();
            DeliveryManage.DAL.Sys_Role dalRole = new DeliveryManage.DAL.Sys_Role();
            List<DeliveryManage.Model.Sys_Role> listRole= dalRole.GetRoleList("");
            foreach (var item in listRole)
            {
                dicRole.Add(item.id, item.role_name);
            }
            ViewData["dicRole"] = dicRole;
            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/User/UserList", "page={0}&pageSize={1}&uid={2}&keywords={3}", "__id__" , pageSize.ToString(), userid.ToString(), keywords.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
            return View();
        }

        public ActionResult UserEdit()
        {
            DeliveryManage.Model.Sys_User user = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            int _id = DTRequest.GetQueryInt("id");
            string action = DTRequest.GetQueryString("action");
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, status = true, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("UserManage", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, status = false, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            DeliveryManage.Model.Sys_User model = new DeliveryManage.Model.Sys_User();
            if (_id > 0)
            {
                model = dal.GetModel(_id);
            }
            ViewBag.AddOrEdit = action;
            #region 会员角色
            DeliveryManage.DAL.Sys_Role roledal = new DeliveryManage.DAL.Sys_Role();
            List<DeliveryManage.Model.Sys_Role> rolelist = roledal.GetRoleList("id>10000");
            ListItemCollection roleitem = new ListItemCollection();
            roleitem.Add(new ListItem("请选择角色...", ""));
            foreach (var item in rolelist)
            {
                if (user.RoleType != 10000)
                {
                    if (user.RoleType == 10001 && item.id == 10005)
                    {
                        roleitem.Add(new ListItem(item.role_name, item.id.ToString()));
                    }
                    else
                    {
                        if (user.RoleType <= item.id && item.id != 10005)
                        {
                            roleitem.Add(new ListItem(item.role_name, item.id.ToString()));
                        }
                    }
                }
                else if (user.RoleType == 10001 && item.id == 10005)
                {
                    roleitem.Add(new ListItem(item.role_name, item.id.ToString()));
                }
                else
                {
                    roleitem.Add(new ListItem(item.role_name, item.id.ToString()));
                }
            }
            ViewData["RoleList"] = new SelectList(roleitem, "value", "text");
            #endregion
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult UserEdit(FormCollection collection)
        {
            try
            {
                bool result = false;
                string action = collection["AddOrEdit"];
                
                DeliveryManage.Model.Sys_User adminmodel = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                #region 数据安防
                if (!ChkAdminLevels("UserManage", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！！" });
                }; //检查权限
                DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                if ((action == "edit" && collection["id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (string.IsNullOrEmpty(collection["Name"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请填写用户名！" });
                }
                if (string.IsNullOrEmpty(collection["Nickname"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请填写昵称！" });
                }
                if (string.IsNullOrEmpty(collection["RoleType"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请选择所属角色！" });
                }
                if (string.IsNullOrEmpty(collection["pwd"]) || collection["pwd"].Length < 6)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入6位数以上的密码！" });
                }
                #endregion

                #region 数据存储
                if (action == "Add")
                {
                    if (int.Parse(collection["ChildCount"]) >= adminmodel.ChildCount && adminmodel.TopUser != 0)
                    {
                        return Json(new ReturnMsgModel { status = false, msg = "没有足够的子用户名额！！" });
                    }
                    string rstr = Convert.ToString(DbHelperSQL.GetSingle(string.Format("select id from Sys_User where Name='{0}'", collection["Name"])));
                    if (!string.IsNullOrEmpty(rstr))
                    {
                        return Json(new ReturnMsgModel { status = false, msg = "该用户已存在！！" });
                    }
                    DeliveryManage.Model.Sys_User newmodel = new Model.Sys_User();
                    if (adminmodel.MaxUserCount <= 0)
                    {
                        return Json(new ReturnMsgModel { status = false, msg = "您的剩余可创子用户数为0！！" });
                    }

                    newmodel.Name = collection["Name"];
                    newmodel.Nickname = collection["Nickname"];
                    newmodel.RoleType = int.Parse(collection["RoleType"]);
                    newmodel.Pwd = collection["Pwd"];
                    newmodel.Pwd= ZyEncrypter.GetMd5str(newmodel.Name + newmodel.Pwd);
                    newmodel.Telephone = collection["Telephone"];
                    newmodel.Email = collection["Email"];
                    newmodel.MaxUserCount = int.Parse(collection["ChildCount"]);
                    newmodel.ChildCount = int.Parse(collection["ChildCount"]);
                    newmodel.TopUser = adminmodel.Id;
                    newmodel.Id = dal.AddUserByProcedure(newmodel);
                    if (newmodel.Id > 0)
                    {
                        if (newmodel.ChildCount > 0)
                        {
                            newmodel.ChildList = new List<Sys_User>();
                        }

                        if (MvcApplication.UserList.ContainsKey(newmodel.TopUser))
                        {
                            if (MvcApplication.UserList[newmodel.TopUser].ChildList == null)
                            {
                                MvcApplication.UserList[newmodel.TopUser].ChildList = new List<Sys_User>();
                            }
                            MvcApplication.UserList[newmodel.TopUser].ChildList.Add(newmodel);
                        }
                        MvcApplication.UserList.Add(newmodel.Id, newmodel);
                        adminmodel.ChildCount-=1;
                        adminmodel.ChildCount -= newmodel.ChildCount;
                        dal.Update(adminmodel);
                        result = true;
                    }
                }
                else
                {
                    DeliveryManage.Model.Sys_User model = dal.GetModel(int.Parse(collection["id"]));
                    if (model != null)
                    {
                        if (model.Name != collection["Name"])
                        {
                            return Json(new ReturnMsgModel { status = false, msg = "用户名不支持修改！！" });
                        }
                        int child = int.Parse(collection["ChildCount"]);
                        if (child < 0)
                        {
                            return Json(new ReturnMsgModel { status = false, msg = "可创建子用户数不能小于0！！" });
                        }
                        if (model.ChildCount != child)
                        {
                            if (adminmodel.TopUser == 0 || adminmodel.ChildCount + model.ChildCount - child >= 0)
                            {
                                adminmodel.ChildCount = adminmodel.ChildCount + model.ChildCount - child;
                                model.MaxUserCount = model.MaxUserCount - model.ChildCount + child;
                                model.ChildCount = child;
                            }
                            else
                            {
                                return Json(new ReturnMsgModel { status = false, msg = "没有足够的子用户名额！！" });
                            }
                        }
                        //修改密码
                        if (!string.IsNullOrEmpty(collection["Pwd"]) && model.Pwd != collection["Pwd"])
                        {
                            model.Pwd = ZyEncrypter.GetMd5str(model.Name + collection["Pwd"]);
                        }
                        model.Name = collection["Name"];
                        model.Nickname = collection["Nickname"];
                        model.RoleType = int.Parse(collection["RoleType"]);
                        model.Telephone = collection["Telephone"];
                        model.Email = collection["Email"];
                        if (dal.Update(model))
                        {
                            MvcApplication.UserList[model.Id] = model;
                            result = true;
                        }
                    }
                }
                #endregion

                if (result == true)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                var a = e.Message;
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" + a });
            }
        }

        [HttpPost]
        public ActionResult UserDelete()
        {
            string ids = DTRequest.GetFormString("id");
            if (!ChkAdminLevels("UserManage", DTEnums.ActionEnum.Delete.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限

            #region 事务处理-执行团队移除操作

            List<String> listString = new List<string>();
            DeliveryManage.Model.Sys_User model = new DeliveryManage.Model.Sys_User();
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            string[] id = ids.Split(',');
            for (int i = 0; i < id.Length; i++)
            {
                if (!string.IsNullOrEmpty(id[i]))
                {
                    model = dal.GetModel(int.Parse(id[i]));

                    DbHelperSQL.ExecuteSql(string.Format("update Sys_User set TopUser={0} where id={1}", model.TopUser, model.Id));//修改自己下属一级代理的推荐人为自己上级
                    //会员关系表：Sys_UserRelation
                    listString.Add(string.Format("delete Sys_UserRelation where  childid={0}", model.Id)); //移除自己的关系
                    DataSet dsfxleveluser = DbHelperSQL.Query(string.Format("select id,TopUser from Sys_User where id in(select distinct(childid) from Sys_UserRelation where userid = {0})", model.Id));
                    for (int j = 0; j < dsfxleveluser.Tables[0].Rows.Count; j++)
                    {
                        int myid = int.Parse(dsfxleveluser.Tables[0].Rows[j]["id"].ToString());
                        int myinvited = int.Parse(dsfxleveluser.Tables[0].Rows[j]["invited"].ToString());
                        //移除原来团队关系
                        listString.Add(string.Format("delete Sys_UserRelation where  childid={0}", myid));

                        DeliveryManage.Model.Sys_User mtuiuser = new DeliveryManage.Model.Sys_User();
                        for (int k = 0; true; k++)
                        {
                            mtuiuser = dal.GetModel(myinvited);
                            if (mtuiuser != null)
                            {
                                //代理等级
                                int fxlevel = k + 1;
                                //添加新团队关系
                                listString.Add(string.Format("insert into Sys_UserRelation values({0},{1},{2},{3})", mtuiuser.Id, mtuiuser.TopUser, myid, fxlevel));
                            }
                            else
                            {
                                break;
                            }
                            myinvited = (int)mtuiuser.TopUser;
                        }
                    }
                    //会员表：Sys_User
                    listString.Add(string.Format("update Sys_User set invit_num -=1 where id in (select userid from Sys_UserRelation where childid = {0} )", model.Id));//修改减去上级团队邀请人数
                    listString.Add(string.Format("delete from Sys_User where id={0}", model.Id));//删除当前会员
                }
            }

            //listString集合提交事务
            if (DbHelperSQL.ExecuteSqlTran(listString) > 0)
            {
                //AddManagerLog(model.id, "UserDelete", "ids:" + ids);
                return Json(new ReturnMsgModel { code = 200, status = true, msg = "调整成功！" });
            }
            else
            {
                //事务未完成则恢复原位
                DbHelperSQL.ExecuteSql(string.Format("update Sys_User set invited={0} where id={1}", model.TopUser, model.Id));
            }
            #endregion
            return Json(new ReturnMsgModel { code = 400, msg = "删除失败！" });
        }
        #endregion

        #region 锁定会员
        [HttpPost]
        public ActionResult UserDisable(int id)
        {
            if (!ChkAdminLevels("UserManage", DTEnums.ActionEnum.Edit.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限
            int _id = id;
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            DeliveryManage.Model.Sys_User model = new DeliveryManage.Model.Sys_User();
            if (_id > 0)
                model = dal.GetModel(_id);
            string msg = "";
            if (model.Status == false)
            {
                model.Status = true;
                msg = "该用户已正常登录";
            }
            else if (model.Status == true)
            {
                model.Status = false;
                msg = "该用户已禁止登录";
            }
            dal.Update(model);
            return Json(new ReturnMsgModel { code = 200, msg = msg });
        }

        [HttpPost]
        public JsonResult SetUserHasSalary(int id)
        {
            if (!ChkAdminLevels("UserManage", DTEnums.ActionEnum.Edit.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限
            int _id = id;
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            DeliveryManage.Model.Sys_User model = new DeliveryManage.Model.Sys_User();
            if (_id > 0)
                model = dal.GetModel(_id);
            string msg = "";
            if (model.IsBasicSalary == false)
            {
                model.IsBasicSalary = true;
                msg = "已设置该用户为包含底薪员工";
            }
            else if (model.IsBasicSalary == true)
            {
                model.IsBasicSalary = false;
                msg = "已设置该用户为非底薪员工";
            }
            dal.Update(model);
            return Json(new ReturnMsgModel { code = 200, msg = msg });
        }

        [HttpPost]
        public JsonResult UserLock()
        {
            if (!ChkAdminLevels("UserManage", DTEnums.ActionEnum.Edit.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！！" });
            }; //检查权限
            int _id = DTRequest.GetFormInt("id");
            string _reason = DTRequest.GetFormString("reason");
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            DeliveryManage.Model.Sys_User model = new DeliveryManage.Model.Sys_User();
            if (_id > 0)
                model = dal.GetModel(_id);
            string msg = "";
            if (model.Status == true)
            {
                model.Status = false;
                msg = "冻结成功";
                dal.Update(model);
            }
            return Json(new ReturnMsgModel { status = true, code = 200, msg = msg });
        }


        [HttpGet]
        public ActionResult UserLockInfo()
        {
            int _id = DTRequest.GetQueryInt("uid");
            string action = DTRequest.GetQueryString("action");
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("AllUser", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限

            ViewBag.LockUserId = _id;
            return View();
        }
        #endregion

        #region 调整团队

        public ActionResult UserTeamEdit()
        {
            int _id = DTRequest.GetQueryInt("id");
            string action = DTRequest.GetQueryString("action");

            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许查看该页面的权限，查看成功！" };
            if (!ChkAdminLevels("UserManage", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看页面的权限，查看失败！" };
                return View();
            }; //检查权限
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            DeliveryManage.Model.Sys_User model = new DeliveryManage.Model.Sys_User();
            if (_id > 0)
            {
                model = dal.GetModel(_id);
            }
            ViewBag.AddOrEdit = action;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult UserTeamEdit(FormCollection collection)
        {
            try
            {
                string action = collection["AddOrEdit"];
                if (!ChkAdminLevels("AllUser", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！" });
                }; //检查权限
                DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                if ((action == "Edit" && collection["id"] == "0") || string.IsNullOrEmpty(collection["adjustid"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (!ChkAdminLevels("AllUser", DTEnums.ActionEnum.View.ToString()))
                {
                    ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看该页面的权限，查看失败！" };
                    return View();
                }; //检查权限

                DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                if (model == null)
                {
                    Response.Write("");
                }

                #region 事务处理-执行团队调整操作
                List<String> listString = new List<string>();
                int userid = int.Parse(collection["id"]);//当前会员
                int invited = int.Parse(collection["invited"]);//当前会员的邀请人
                int adjustid = int.Parse(collection["adjustid"]);//所要调整加入的团队组会员(邀请人)
                int invit_num = int.Parse(collection["invit_num"]) + 1;//当前会员团队人数

                //判断调整用户代码是否属于自己下属
                //暂时放开限制、调整团队时可以随意调整
                int count = 0;
                //count = (int)DbHelperSQL.GetSingle(string.Format("select COUNT(distinct(childid)) from Sys_UserRelation where (userid={0} or childid={0}) and childid={1}", model.id, adjustid));
                //if (count==0)
                //{
                //    return Json(new ReturnMsgModel { status = false, msg = "该调整用户代码不属于自己下属会员！" });
                //}
                if (adjustid == invited)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "新团队未发生改变,调整失败！" });
                }
                //else if (adjustid == userid)
                //{
                //    return Json(new ReturnMsgModel { status = false, msg = "团队组账户不能为当前用户代码，不能重复调整！" });
                //}
                count = (int)DbHelperSQL.GetSingle(string.Format("select COUNT(distinct(childid)) from Sys_UserRelation where childid={0}", adjustid));
                if (count == 0)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "不存在的团队！" });
                }
                
                ////判断所要调整的团队关系组是否是自己下属
                //count = (int)DbHelperSQL.GetSingle(string.Format("select COUNT(distinct(childid)) from Sys_UserRelation where userid={0} and childid={1}", userid,adjustid));
                //if (count>0)
                //{
                //    return Json(new ReturnMsgModel { status = false, msg = "不能调整到比自己低的代理等级下！" });
                //}
                //减去当前会员所有上级的团队人数
                listString.Add(string.Format("update Sys_User set invit_num-={0} where id in(select userid from Sys_UserRelation where childid={1})", invit_num, userid));
                listString.Add(string.Format("update Sys_User set invit_num=0 where id in(select userid from Sys_UserRelation where childid={0} and invit_num<0)", userid));

                //修改当前会员邀请人
                DbHelperSQL.ExecuteSql(string.Format("update Sys_User set invited={0} where id={1}", adjustid, userid));
                //修改下属关系
                DataSet dsfxleveluser = DbHelperSQL.Query(string.Format("select id,invited from Sys_User where id in(select distinct(childid) from Sys_UserRelation where userid = {0} or childid={0})", userid));
                for (int i = 0; i < dsfxleveluser.Tables[0].Rows.Count; i++)
                {
                    int myid = int.Parse(dsfxleveluser.Tables[0].Rows[i]["id"].ToString());
                    int myinvited = int.Parse(dsfxleveluser.Tables[0].Rows[i]["invited"].ToString());
                    //移除原来团队关系
                    listString.Add(string.Format("delete Sys_UserRelation where  childid={0}", myid));

                    DeliveryManage.Model.Sys_User mtuiuser = new DeliveryManage.Model.Sys_User();
                    for (int j = 0; true; j++)
                    {
                        mtuiuser = dal.GetModel(myinvited);
                        if (mtuiuser != null)
                        {
                            //代理等级
                            int fxlevel = j + 1;
                            //添加新团队关系
                            listString.Add(string.Format("insert into Sys_UserRelation values({0},{1},{2},{3})", mtuiuser.Id, mtuiuser.TopUser, myid, fxlevel));
                        }
                        else
                        {
                            break;
                        }
                        myinvited = (int)mtuiuser.TopUser;
                    }
                }

                //加上当前会员所有上级的团队人数
                listString.Add(string.Format("update Sys_User set invit_num+={0} where id in(select userid from Sys_UserRelation where childid={1})", invit_num, userid));

                //listString集合提交事务
                if (DbHelperSQL.ExecuteSqlTran(listString) > 0)
                {
                    //AddManagerLog(model.id, "UserTeamEdit", userid + ":" + invited + "—>" + adjustid);
                    return Json(new ReturnMsgModel { code = adjustid, status = true, msg = "调整成功！" });
                }
                else
                {
                    //事务未完成则恢复原位
                    DbHelperSQL.ExecuteSql(string.Format("update Sys_User set invited={0} where id={1}", invited, userid));
                }
                #endregion
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "调整失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
        }

        [HttpPost]
        public JsonResult UserTeamEditPL()
        {
            try
            {
                if (!ChkAdminLevels("UserSource", DTEnums.ActionEnum.Edit.ToString()))
                {
                    return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！" });
                }; //检查权限
                string ids = DTRequest.GetFormString("id");
                int newparuserid = DTRequest.GetFormInt("paruser");
                DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                if (!dal.Exists(newparuserid))
                {
                    return Json(new ReturnMsgModel { status = false, code = 400, msg = "要调入的新上级会员不存在，操作失败！" });
                }

                List<String> listString = new List<string>();
                List<String> restorelistString = new List<string>();
                #region 事务处理-执行团队调整操作

                string[] userids = ids.Split(',');
                for (int k = 0; k < userids.Length; k++)
                {
                    if (!string.IsNullOrEmpty(userids[k]))
                    {
                        DeliveryManage.Model.Sys_User user = dal.GetModel(Convert.ToInt32(userids[k]));//等待调整的会员
                        #region 执行团队调整操作
                        int invit_num = Convert.ToInt32(user.ChildCount) + 1;//当前会员团队人数
                        if (newparuserid == user.TopUser)
                        {
                            continue;//要调入的组和原来相同，不处理
                        }
                        else if (newparuserid == user.Id)
                        {
                            continue;//要调入的组为自己，不处理
                        }
                        //减去当前会员所有上级的团队人数
                        listString.Add(string.Format("update Sys_User set ChildCount-={0} where id in(select userid from Sys_UserRelation where childid={1})", invit_num, user.Id));
                        listString.Add(string.Format("update Sys_User set ChildCount=0 where id in(select userid from Sys_UserRelation where childid={0} and ChildCount<0)", user.Id));

                        //事务未完成则恢复原位
                        restorelistString.Add(string.Format("update Sys_User set TopUser={0} where id={1}", user.TopUser, user.Id));
                        //修改当前会员上级为新指定的上级、并设置为已调组状态，方便区分
                        DeliveryManage.Model.Sys_User muser = dal.GetModel(newparuserid);
                        DbHelperSQL.ExecuteSql(string.Format("update Sys_User set TopUser={0} where id={1}", newparuserid, user.Id));

                        //修改当前会员的新下属关系
                        DataSet dsfxleveluser = DbHelperSQL.Query(string.Format("select id,TopUser from Sys_User where id in(select distinct(childid) from Sys_UserRelation where userid = {0} or childid={0})", user.Id));
                        for (int i = 0; i < dsfxleveluser.Tables[0].Rows.Count; i++)
                        {
                            int myid = int.Parse(dsfxleveluser.Tables[0].Rows[i]["id"].ToString());
                            int myinvited = int.Parse(dsfxleveluser.Tables[0].Rows[i]["invited"].ToString());
                            //移除下属原来团队关系
                            listString.Add(string.Format("delete Sys_UserRelation where  childid={0}", myid));
                            DeliveryManage.Model.Sys_User mtuiuser = new DeliveryManage.Model.Sys_User();
                            for (int j = 0; true; j++)
                            {
                                mtuiuser = dal.GetModel(myinvited);
                                if (mtuiuser != null)
                                {
                                    //代理等级
                                    int fxlevel = j + 1;
                                    //添加新团队关系
                                    listString.Add(string.Format("insert into Sys_UserRelation values({0},{1},{2},{3})", mtuiuser.Id, mtuiuser.TopUser, myid, fxlevel));
                                }
                                else
                                {
                                    break;
                                }
                                myinvited = (int)mtuiuser.TopUser;
                            }
                        }

                        //修改当前会员调整后所有新上级的团队人数
                        listString.Add(string.Format("update Sys_User set ChildCount+={0} where id in(select userid from Sys_UserRelation where childid={1})", invit_num, user.Id));

                        #endregion
                    }
                }
                //listString集合提交事务
                if (DbHelperSQL.ExecuteSqlTran(listString) > 0)
                {
                    return Json(new ReturnMsgModel { status = true, code = 200, msg = "调整成功！" });
                }
                else
                {
                    //事务未完成则恢复原位
                    DbHelperSQL.ExecuteSqlTran(restorelistString);
                }
                #endregion
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "调整失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "调整失败！" });
            }
        }
        #endregion

    }
}
